from flask import request,session,render_template,json
from application.colleague import colleague
from db_util.models import Colleague,db,User,Schedule,Events
from sqlalchemy import and_,or_

#######################################
#         界面跳转：同事模块
#######################################
#跳转到添加同事界面
@colleague.route("/colleague/to_add_colleague")
def to_add_colleague():
    return render_template("colleague/add_colleague.html")

#跳转到同事日程界面
@colleague.route("/colleague/to_colleague_schedule")
def to_colleague_schedule():
    colleague_id = request.args.get("colleague_id");
    user_id = session['user_id'];
    session['colleague_id'] = colleague_id;
    colleague = db.session.query(Colleague).filter(and_(Colleague.user_id == colleague_id,Colleague.colleague_id == user_id)).first();
    if(session['user_id'] == colleague_id):
        return render_template("user/user_index.html");
    user_info_list = db.session.query(User).filter(User.id != session['user_id']).all();
    for item in user_info_list:
        colleague_info = db.session.query(Colleague).filter(and_(Colleague.user_id == session['user_id'], Colleague.colleague_id == item.id)).first();
        if (colleague_info):
            item.permission = colleague_info.permission;

    if(colleague.permission == 2):
        db.session.close();
        return render_template("user/colleague_index.html",user_info_list=user_info_list,jumpRes = "无权限查看！");
    else:
        db.session.close();
        return render_template("user/colleague_schedule.html",colleague_id=colleague_id)

#跳转到同事待办界面
@colleague.route("/colleague/to_colleague_events")
def to_colleague_events():
    colleague_id = request.args.get("colleague_id");
    user_id = session['user_id'];
    session['colleague_id'] = colleague_id;
    colleague = db.session.query(Colleague).filter(
        and_(Colleague.user_id == colleague_id, Colleague.colleague_id == user_id)).first();
    if (session['user_id'] == colleague_id):
        return render_template("user/user_todolist.html");
    print("################" + str(colleague.permission));
    user_info_list = db.session.query(User).filter(User.id != session['user_id']).all();
    for item in user_info_list:
        colleague_info = db.session.query(Colleague).filter(
            and_(Colleague.user_id == session['user_id'], Colleague.colleague_id == item.id)).first();
        if (colleague_info):
            item.permission = colleague_info.permission;

    if (colleague.permission == 2):
        db.session.close();
        return render_template("user/colleague_index.html", user_info_list=user_info_list, jumpRes="无权限查看！");
    else:
        db.session.close();
        return render_template("user/colleague_events.html",colleague_id=colleague_id)


#######################################
#         定义接口：同事模块
#######################################
#同事列表
@colleague.route("/colleague/colleague_list",methods=['GET','POST'])
def colleague_list():
    # if(session['user_id']==0):
    #     return("尚未登陆")
    # user_id = session["user_id"]
    # colleague_list = db.session.query(Colleague).filter(Colleague.user_id == user_id).all();
    # colleague_info_list = [];
    # if(colleague_list):
    #     for colleague_item in colleague_list:
    #         user_info_item_list = db.session.query(User).filter(User.id == colleague_item.colleague_id).all();
    #         if(user_info_item_list):
    #             user = user_info_item_list[0];
    #             colleague_info_list.append(user);
    user_info_list = db.session.query(User).filter(User.id != session['user_id']).all();
    try:
        #读取用户权限列表
        for item in user_info_list:
            colleague_info = db.session.query(Colleague).filter(and_(Colleague.user_id == session['user_id'],Colleague.colleague_id == item.id)).first();
            if(colleague_info):
                item.permission = colleague_info.permission;
        return render_template("user/colleague_index.html",
                               user_info_list = user_info_list);
    finally:
        db.session.close();

#同事新增
@colleague.route("/colleague/colleague_add",methods=['GET','POST'])
def colleague_add():
    user_id = session["user_id"]
    data = request.get_data("data")
    data = bytes.decode(data);

    if (len(data) > 0):
        data = json.loads(data)
    print(data);
    nickName = data['nickName']
    user_list = db.session.query(User).filter(User.nickname == nickName).all()
    if(user_list):
        colleague = Colleague();
        user = user_list[0]
        colleague.user_id = user_id
        colleague.colleague_id = user.id
        colleague.remark="同事"
        colleague.permission=1
        db.session.add(colleague)
        db.session.commit()
        db.session.close();
        return render_template("SUCCESS")
    else:
        db.session.close();
        return("ERROR")

#同事删除
@colleague.route("/colleague/colleague_delete",methods=['GET','POST'])
def colleague_delete():
    user_id = session["user_id"]
    data = request.get_data("data")
    data = bytes.decode(data);

    if (len(data) > 0):
        data = json.loads(data)
    print(data);
    colleague_id = data['colleague_id']
    colleague = db.session.query(Colleague).filter(and_(Colleague.user_id == user_id,colleague_id == Colleague.colleague_id)).first()
    if(colleague):
        db.session.execute('delete from colleague where id=:id', {'id': colleague.id})
        db.session.commit()
        db.session.close();
        return ("删除同事成功")
    else:
        db.session.close();
        return ("删除同事失败")

#同事查找（列表查找）
@colleague.route("/colleague/colleague_select",methods=['GET','POST'])
def colleague_find_inlist():
    # data = request.get_data("data")
    # data = bytes.decode(data);
    #
    # if (len(data) > 0):
    #     data = json.loads(data)
    # print(data);
    # user_name = data['user_name']
    user_name = request.args.get("user_name");
    colleague_list = db.session.query(User).filter(or_(User.username.like('%'+user_name+'%'),User.nickname.like('%'+user_name+'%'))).all();
    user_info_list = db.session.query(User).all();
    db.session.close();
    if(colleague_list):
        db.session.close();
        return render_template("user/colleague_index.html",user_info_list = user_info_list,colleague_list = colleague_list)
    else:
        db.session.close();
        return("ERROR")


#同事权限修改
@colleague.route("/colleague/colleague_permission_update",methods=['GET','POST'])
def colleague_permission_update():
    data = request.get_data("data")
    data = bytes.decode(data);

    if (len(data) > 0):
        data = json.loads(data)
    print(data);
    user_id = session['user_id'];
    colleague_id = data['user_id'];
    colleague_permission = data['user_permission'];
    colleague = db.session.query(Colleague).filter(and_(Colleague.user_id == user_id,Colleague.colleague_id == colleague_id)).first();
    if(colleague):
        colleague.permission = colleague_permission;
        db.session.merge(colleague);
        db.session.commit();
        db.session.close();
        return("SUCCESS");
    db.session.close();
    return("ERROR");

#被添加验证
@colleague.route("/colleague/colleague_judge",methods=['GET','POST'])
def colleague_judge():
    return

#查看同事代办
@colleague.route("/colleague/colleague_events",methods=['GET','POST'])
def schedule_list():
    colleague_id = request.args.get("colleague_id")
    schedule_list = db.session.query(Schedule).filter(Schedule.user_id == colleague_id).all()

    res = "["
    i = 0;
    for item in schedule_list:
        if i != 0:
            res = res + ","
        if item.finished == 0:
            item_str = "{\"start\":\"" + item.start_time.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"end\":\"" + item.end_time.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"title\":\"" + item.title + "\",\"id\":\"" + str(
                item.id) + "\",\"color\":\"red\"}";
        else:
            item_str = "{\"start\":\"" + item.start_time.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"end\":\"" + item.end_time.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"title\":\"" + item.title + "\",\"id\":\"" + str(
                item.id) + "\",\"color\":\"blue\"}";
        i = i + 1
        res = res + item_str;
        print(i);
    res = res + "]"
    schedule_list = json.dumps(res)
    print(schedule_list)
    db.session.close();
    return schedule_list

#查看同事日程
@colleague.route("/colleague/colleague_schedule",methods=['GET','POST'])
def events_list():
    colleague_id = request.args.get("colleague_id");
    events_list = db.session.query(Events).filter(Events.user_id == colleague_id).all()
    res = "["
    i = 0;
    for item in events_list:
        if i != 0:
            res = res + ","
        if item.level == 0:
            item_str = "{\"start\":\"" + item.start_date.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"end\":\"" + item.end_date.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"title\":\"" + item.text + "\",\"id\":\"" + str(
                item.id) + "\",\"color\":\"blue\"}";
        elif item.level == 1:
            item_str = "{\"start\":\"" + item.start_date.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"end\":\"" + item.end_date.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"title\":\"" + item.text + "\",\"id\":\"" + str(
                item.id) + "\",\"color\":\"orange\"}";
        else:
            item_str = "{\"start\":\"" + item.start_date.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"end\":\"" + item.end_date.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"title\":\"" + item.text + "\",\"id\":\"" + str(
                item.id) + "\",\"color\":\"red\"}";
        i = i + 1
        res = res + item_str;
        print(i);
    res = res + "]"
    events_list = json.dumps(res)
    print(events_list)
    db.session.close();
    return events_list